#===============================================================
# calculate distance nomalized data
#---------------------------------------------------------------
# read treat
data1 <- read.table(file.choose(), header=F)
# read control
data2 <- read.table(file.choose(), header=F)

v <- ifelse(data2[[length(data2)]] > 3, data1[[length(data1)]]/data2[[length(data2)]], 0)

mat <- matrix(v, nrow=sqrt(length(v)), byrow=T)
d = dim(mat)[1]
n = dim(mat)[2]
mat.rev = t(mat[d+1-c(1:d), ])

mat.conv = mat.rev

#---------------------------------------------------------------
# end
#===============================================================


#===============================================================
# HiC style normalization
#---------------------------------------------------------------
library(RColorBrewer)
c <- rev(colorRampPalette(brewer.pal(10, "RdBu"))(100))	# gentle color

corCalc <- function(m){
	new = m
	d = dim(m)[1]
	for(i in 1:d){
		for(j in 1:d){
			corValue = cor(m[i,],rev(m[,j]))
			new[i,j] = corValue
		}
	}
	new
}

mat.cor <- corCalc(mat.rev)

mat.conv <- ifelse(mat.cor > 0.5, 0.5, mat.cor)
mat.conv <- ifelse(mat.conv < -0.5, -0.5, mat.conv)



#===============================================================
# SCN normalization
#---------------------------------------------------------------

SCN <- function(m){
	new = m
	d = dim(m)[1]
	for(i in 1:d){
		sq <- sqrt(sum(m[i,]**2))
		sq <- ifelse(sq == 0, 1, sq)
		new[i,] <- m[i,]/sq
	}
	new2 = new
	for(i in 1:d){
		sq <- sqrt(sum(new[,i]**2))
		sq <- ifelse(sq == 0, 1, sq)
		new2[,i] <- new[,i]/sq
	}
	new2
}

multiSCN <- function(m, times){
	for(i in 1:times){
		m = SCN(m)
	}
	m
}

mat.scn5 <- multiSCN(mat.rev, 5)
mat.scn5.cor<- corCalc(mat.scn5)

maxVal <- 0.15
mat.conv <- ifelse(mat.scn5 > maxVal, maxVal, mat.scn5)

mat.conv <- ifelse(mat.scn5.cor > 0.5, 0.5, mat.scn5.cor)
mat.conv <- ifelse(mat.conv < -0.5, -0.5, mat.conv)

#===============================================================
# Converting format
#---------------------------------------------------------------

### convert to original matrix
d = dim(mat.scn5.cor)[1]
n = dim(mat.scn5.cor)[2]
mat.scn5.cor.original <- (t(mat.scn5.cor))[d+1-c(1:d),]

### convert for output
output.data <- as.numeric(t(mat.scn5.cor.original))

### making dataframe
output <- data.frame(loc1=data1$V1, loc2=data1$V2, score=output.data)
head(output)

#===============================================================
# Save calculated score
#---------------------------------------------------------------
write.table(output, file=file.choose(new=T),row.names=F, col.names=F, quote=F, sep="\t", eol="\n")











